package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.EmpDao;
import entity.Emp;
import utils.R;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "AddServlet",urlPatterns = "/add")
public class AddServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String mobile = request.getParameter("mobile");
        String email = request.getParameter("email");
        Integer isDelete = 0;

        Emp emp = new Emp();
        emp.setEmail(email);
        emp.setMobile(mobile);
        emp.setPassword(password);
        emp.setUsername(username);
        emp.setIsDelete(isDelete);
        System.out.println(username+","+password+","+mobile+","+email);
        EmpDao empDao = new EmpDao();
        Integer row = empDao.insert(emp);
        //response.sendRedirect("/emp/emplist");
        R json = new R();
        if(row==1){
            json.setState(1);
            /*json.setMessage("");*/
        }else {
            json.setMessage("插入失败");
        }
        //把得到的集合转成json字符串
        ObjectMapper om = new ObjectMapper();
        String result = om.writeValueAsString(json);
        //把json字符串返回给客户端   text/html 表示返回的数据是文本或标签
        //application/json告诉客户端返回的是Json对象 客户端接收到数据时不需要再进行转换
        response.setContentType("application/json;charset=utf-8");
        PrintWriter pw = response.getWriter();
        pw.print(result);
        pw.close();
    }
}
